package top.hitotright.springmemo.controller;

import org.hibernate.Session;
import org.hibernate.SessionFactory;
import org.hibernate.cfg.Configuration;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.bind.annotation.RestController;
import top.hitotright.springmemo.model.User;

@RestController
public class UserController {

    @RequestMapping("/user")
    public String getUser(@RequestParam(value="id", defaultValue="") int userId){
        return "userId:"+userId;
    }

    @RequestMapping("/user/add")
    @ResponseBody
    public String addUser(String name,String email){
        // 1、加载配置文件
        Configuration configuration = new Configuration().configure();
        // 2、创建Session工厂
        SessionFactory factory = configuration.buildSessionFactory();
        // 3、创建Session对象
        Session session = factory.openSession();
        // 4、操作数据
        session.beginTransaction();
        String result ="";
        User user =  new User(name, email);
        result+="保存结果:"+ session.save(user);
        result+="\n";
        session.getTransaction().commit();
        result+="反馈用户编号:"+ user.getUserId();
        // 5、关闭
        session.close();
        return result;
    }
}
